package com.worldsensing.chartutils.wrapper;

import java.util.Random;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.visualization.client.visualizations.corechart.Options;
/**
 * wrapper of the js library  to create charts. Offers connection and charting methods.
 * @author xvilajosana
 *
 */

public class CubeWrapper {

	
	public  final int TABLE = 0;
	public  final int PIE = 1;
	public  final int LINE = 2;
	public  final int BAR = 3;
	public  final int COLUMN = 4;
	public  final int AREA = 5;
	
	/**
	 * gets the connection with the cube server
	 * @param url
	 * @param user
	 * @param pwd
	 * @param schema
	 * @return
	 */
	public CubeConnection getCubeConnection(String url,String user,String pwd,String schema){
		CubeConnection c= new CubeConnection( url, user, pwd, schema);
		c.setConnection(this.getConnection( url, user, pwd, schema));
		return c;
	}
	
	/**
	 * Native method to get the connection
	 * @param url
	 * @param user
	 * @param pwd
	 * @param schema
	 * @return
	 */
	
	private native JavaScriptObject getConnection(String url,String user,String pwd,String schema) /*-{

    	var conn = $wnd.vizHelper.setupConnection({
			url : url,
			userName : user,
			userPassword : pwd
			},schema);
		
		    conn.sendRequest(new $wnd.viz.GetSchemasGviRequest(), {
            onSuccess : function(gviTable) {
            //do nothing
           	//     alert("The icCube server is containing " + gviTable.getRowCount() + " schemas.")
            }
        });
   		return conn;     
}-*/;

/**
 * Creates a chart according to the type with the specified options from the mdx query	
 * @param conn
 * @param mdx
 * @return Widget
 */
	
public Widget createChart(CubeConnection conn,int type,Options options,String mdx) throws Exception{
	FlowPanel result= new FlowPanel();
	
	if (type<TABLE || type > AREA) throw new Exception("Invalid chart type");
	result.getElement().setId("chart"+new Random().nextInt());
	
	result.setVisible(true);
	result.setWidth("600px");
	result.setHeight("400px");
	RootPanel.get().add(result);//trick to add the flowpanel to the document as the js method requires that the element is placed in the root document.
	createJSChart(conn.getConnection(),result.getElement().getId(),conn.getSchema(),type,options,mdx);
	result.removeFromParent();//after having the chart created we can remove it from the root panel as it is already drawn.
	return result;
}
	
/**
 * Native method that creates the chart
 * @param conn
 * @param panelName
 * @param schema
 * @param mdx
 */

private native void createJSChart(JavaScriptObject conn,String panelName,String schema,int type,JavaScriptObject options,String mdx)/*-{
	//native code.
	// List of schemas logic : create manager, create and bind widget
	var schemasMgr = new  $wnd.viz.QueryManager(conn);
	var schemas = new  $wnd.vizUi.DropDownList("schemas", null, null,schema);
    schemasMgr.addResultWidget(schemas);

	// Logic for the MDX query : create first a manager

	var queryMgr = new  $wnd.viz.QueryManager(conn);

	// Use a Google visualization chart.
	var charttype;
	
	if (type == this.@com.worldsensing.chartutils.wrapper.CubeWrapper::TABLE){
		charttype=$wnd.vizGoogle.ChartChooser.TABLE;
	}else if (type == this.@com.worldsensing.chartutils.wrapper.CubeWrapper::PIE){
		charttype=$wnd.vizGoogle.ChartChooser.PIE;
	}else if (type == this.@com.worldsensing.chartutils.wrapper.CubeWrapper::LINE){
		charttype=$wnd.vizGoogle.ChartChooser.LINE;
	}else if (type == this.@com.worldsensing.chartutils.wrapper.CubeWrapper::BAR){
		charttype=$wnd.vizGoogle.ChartChooser.BAR;
	}else if (type == this.@com.worldsensing.chartutils.wrapper.CubeWrapper::COLUMN){
		charttype=$wnd.vizGoogle.ChartChooser.COLUMN;
	}else if (type == this.@com.worldsensing.chartutils.wrapper.CubeWrapper::AREA){
		charttype=$wnd.vizGoogle.ChartChooser.AREA;
	}
	
	var chart = new  $wnd.vizGoogle.MutableChart(panelName,
			 charttype, options);
	queryMgr.addResultWidget(chart);

	// Setup an action to drilldown into a selected member in the table.

	chart.cellClicked(new  $wnd.viz.ActionDrilldown(queryMgr));

	// Keep a history of the drilldown requests.

	var history = new  $wnd.vizUi.HistoryButton("history", queryMgr);

	//Let's start by setting the schema into the connection on a combo change event

	schemas.change(function(entities) {
		conn.setSchemaName(entities[0].name);
		//$wnd.alert(entities[0].name);			
	});

	// On click button execute the query as defined in the text area (and clear the previous request history)
	var m=mdx;
	
	queryMgr.executeRequest(new $wnd.viz.MdxGviRequest(m));
	history.clear();
	// Once everything is finished execute the request to get the list of schemas

	schemasMgr.executeRequest(new  $wnd.viz.GetSchemasGviRequest());
}-*/;

}
